<script setup lang="ts">
import type { TempTableInfo } from "@/api/template/table";
import { onActivated, onMounted, reactive, ref } from "vue";
import type { ButtonsCallBackParams, PlusColumn } from "plus-pro-components";
import { ElMessageBox } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { message } from "@/utils/message";
import { buttons, tableColumns } from "./utils/hooks";
import $request, { tableEmptyText, plusPageRef } from "./utils/request";

import DialogForm from "./form.vue";

defineOptions({
  name: "SystemMenu"
});

// 状态参数
const state = reactive({
  // 是否已初始化
  hasInit: false,
  // 页面加载中
  isLoading: true,
  // 表格已选项
  selectedIds: []
});

// 渲染配置
const renderColumns = ref<PlusColumn[]>([]);

// 当前选中数据
const currentRow = ref<TempTableInfo>();

// 组件
const dialogFormRef = ref();

// 表格事件操作（点击）
const handleTableAction = async (type: string) => {
  switch (type) {
    case "create":
      // 新增
      dialogFormRef.value.handleOpen();
      break;
    case "delete":
      // 批量删除
      onDelete(true);
      break;
    default:
      break;
  }
};

// 表格按钮操作（点击）
const handleTableOption = async ({ row, buttonRow }: ButtonsCallBackParams) => {
  currentRow.value = row as TempTableInfo;
  switch (buttonRow.code) {
    case "add":
      // 新增
      dialogFormRef.value.handleOpen({
        type: row.id
      });
      break;
    case "update":
      // 编辑
      dialogFormRef.value.handleOpen({
        id: row.id
      });
      break;
    case "delete":
      // 删除
      onDelete(false);
      break;
  }
};

// 表格选择
const handleTableSelect = (data: TempTableInfo[]) => {
  state.selectedIds = [...data].map(item => item.id);
};

// 执行删除
const onDelete = async (isBatch: boolean) => {
  if (isBatch) {
    if (!state.selectedIds.length) {
      message("请选择数据！", { type: "warning" });
    } else {
      await ElMessageBox.confirm("确定删除所选数据", "提示");
      await $request.delete.batch(state.selectedIds);
    }
  } else {
    await $request.delete.remove(currentRow.value.id);
  }
  message("删除成功", { type: "success" });
  refresh();
};

// 刷新列表
const refresh = async () => {
  await plusPageRef.value?.getList();
};

// ----- 初始化缓存 -----

onMounted(async () => {
  state.isLoading = true;
  await $request.event.onPageShow(false);
  renderColumns.value = tableColumns;
  state.hasInit = true;
  state.isLoading = false;
});

onActivated(async () => {
  if (state.hasInit) {
    state.isLoading = true;
    renderColumns.value = [];
    await $request.event.onPageShow(true);
    renderColumns.value = tableColumns;
    state.isLoading = false;
  }
});
</script>

<template>
  <div class="page-container">
    <plus-page
      ref="plusPageRef"
      v-loading="state.isLoading"
      element-loading-text="数据读取中..."
      :request="$request.get.treeList"
      :columns="renderColumns"
      :search="{
        showNumber: 3,
        labelWidth: '100px',
        colProps: {
          xs: 24,
          md: 12,
          lg: 6,
          xl: 4
        },
        labelPosition: 'right'
      }"
      :table="{
        emptyText: tableEmptyText,
        isSelection: true,
        actionBar: {
          showNumber: 4,
          buttons,
          width: 150,
          actionBarTableColumnProps: {
            align: 'center'
          }
        },
        adaptive: {
          offsetBottom: 32
        },
        defaultExpandAll: true,
        onClickAction: handleTableOption,
        onSelectionChange: handleTableSelect
      }"
      :pagination="false"
    >
      <template #table-title>
        <el-row class="button-row">
          <el-button
            type="success"
            :icon="Plus"
            plain
            @click="handleTableAction('create')"
          >
            新增菜单
          </el-button>
          <el-button
            :icon="Delete"
            type="danger"
            plain
            :disabled="!state.selectedIds.length"
            @click="handleTableAction('delete')"
          >
            批量删除
          </el-button>
        </el-row>
      </template>
    </plus-page>
    <DialogForm ref="dialogFormRef" @ok="refresh" />
  </div>
</template>

<style lang="scss" scoped>
//
</style>
